package com.leetcode.weekly.contest.no235th;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 覃国强
 * @date 2021-04-04 11:23
 */
public class A03_绝对差值和 {


  static
  class Solution {
    public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {
      int mod = 10_0000_0007;
      int result = 0;
      int maxAbs = Integer.MIN_VALUE;
      List<Integer> maxAbsIndexes = new ArrayList<>();
      for (int i = 0; i < nums1.length; ++i) {
        int abs = Math.abs(nums1[i] - nums2[i]);
        if (maxAbs < abs) {
          maxAbsIndexes.clear();
          maxAbsIndexes.add(i);
          maxAbs = abs;
        } else if (maxAbs == abs && isMatch(maxAbsIndexes, i, nums2)) {
          maxAbsIndexes.add(i);
        }
        result = (result % mod + abs % mod) % mod;
      }

      int minAbs = Integer.MAX_VALUE;

      for (int k : nums1) {
        for (int j : maxAbsIndexes) {
          int abs = Math.abs(k - nums2[j]);
          if (minAbs > abs) {
            minAbs = abs;
          }
        }
      }

      result = (result % mod - maxAbs % mod) % mod;
      result = (result % mod + minAbs % mod) % mod;

      return result;
    }

    private boolean isMatch(List<Integer> maxAbsIndexes, int i, int[] nums2) {
      for (int index : maxAbsIndexes) {
        if (nums2[i] == nums2[index]) {
          return false;
        }
      }
      return true;
    }
  }

}
